package com.broadengate.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.broadengate.bean.SessionInfo;

/**
 * Seesion拦截器
 * 
 * @author 木子传
 * 
 */
public class SessionInterceptor extends HandlerInterceptorAdapter
{
    private List<String> excludeUrls;// 不需要拦截的资源
    
    /**
     * 请求前判断Session是否超时
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        // 获取Session对象
        SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("session");
        
        String requestUri = request.getRequestURI();
        
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        
        if (url.indexOf("images") > -1 || url.indexOf("css") > -1 || url.indexOf("js") > -1
                || excludeUrls.contains(url))
        {// 如果要访问的资源是不需要验证的
            return true;
        }
        
        if (sessionInfo == null || sessionInfo.getUserId() == 0)
        {
            request.setAttribute("msg", "您还没有登录或登录已超时，请重新登录，然后再刷新本功能！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return false;
        }
        else
        {
            return true;
        }
    }
    
    public List<String> getExcludeUrls()
    {
        return excludeUrls;
    }
    
    public void setExcludeUrls(List<String> excludeUrls)
    {
        this.excludeUrls = excludeUrls;
    }
    
}
